#pragma once

#include <iostream>
#include <string>
#include <functional>

#include "sock.hpp"

using namespace std;

namespace select_ns
{
    class selectServer
    {
        static const uint16_t gport = 8080;
        static const int defaultfd = -1;
        static const int fdnum = sizeof(fd_set) * 8;
        using func_t = function<string (const string&)>;
    public:
        selectServer(func_t f, int port = gport)
            : _port(port), _listensock(-1), _func(f),_fdarray(nullptr)
        {
        }
        void Print()
        {
            cout << "fd list:";
            for (int i = 0; i < fdnum; ++i)
            {
                if (_fdarray[i] != defaultfd)
                    cout << _fdarray[i] << " ";
            }
            cout << endl;
        }

        void initserver()
        {
            _listensock = sock::Socket();
            sock::Bind(_listensock, _port);
            sock::Listen(_listensock);
            _fdarray = new int[fdnum];
            for (int i = 0; i < fdnum; ++i)
                _fdarray[i] = defaultfd;
            _fdarray[0] = _listensock;
        }

        void Accepter(int listensock)
        {
            string clientip;
            uint16_t clientport = 0;
            int sock = sock::Accept(listensock, &clientip, &clientport);
            if (sock < 0)
                return;
            else
                logMessage(NORMAL, "accept success [%s, %d]", clientip.c_str(), clientport);

            int i = 0;
            for (; i < fdnum; ++i)
            {
                if (_fdarray[i] != defaultfd)
                    continue;
                else
                    break;
            }
            if (i == fdnum)
            {
                logMessage(WARNING, "连接满了，添加不上了");
                close(sock);
            }
            else
            {
                _fdarray[i] = sock;
            }
            Print();
        }
        void Recver(int sock, int pos)
        {
            char buffer[1024];
            int n = recv(sock, &buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                logMessage(NORMAL, "clinet# %s", buffer);
            }
            else if (n == 0)
            {
                close(sock);
                _fdarray[pos] = defaultfd;
                logMessage(DEBUG, "client quit, meto");
                return ;
            }
            else
            {
                close(sock);
                _fdarray[pos] = defaultfd;
                logMessage(DEBUG, "client quit, meto");
                return ;
            }

            string responce = _func(buffer);
            write(sock, responce.c_str(), responce.size());
        }
        // 在handlerevent rfds中，可能不止一个文件描述符就绪，而是有多个
        void HandlerReadEvent(fd_set &fds)
        {
            for (int i = 0; i < fdnum; ++i)
            {
                // 过滤掉非法的fd
                if (_fdarray[i] == defaultfd)
                    continue;

                if (FD_ISSET(_fdarray[i], &fds) && _listensock == _fdarray[i])
                {
                    Accepter(_listensock);
                }
                else if(FD_ISSET(_fdarray[i], &fds))
                {
                    Recver(_fdarray[i], i);
                }
            }
        }
        void start()
        {

            for (;;)
            {
                fd_set rfds;
                FD_ZERO(&rfds);
                int maxfd = _fdarray[0];
                for (int i = 0; i < fdnum; ++i)
                {
                    if (_fdarray[i] == defaultfd)
                        continue;
                    FD_SET(_fdarray[i], &rfds); // 合法的fd 全部添加到文件描述符集中
                    if (maxfd < _fdarray[i])
                        maxfd = _fdarray[i];
                }

                // struct timeval timeout = {1, 0};

                // int n = select(_listensock + 1, &rfds, nullptr, nullptr, &timeout);
                int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout...");
                    break;
                case -1:
                    logMessage(ERROR, "select error, errcode: %d err describe: %s", errno, strerror(errno));
                    break;
                default:
                    logMessage(NORMAL, "have event ready!");
                    HandlerReadEvent(rfds);
                    break;
                }

                // string clientip;
                // uint16_t clientport = 0;
                // int sock = sock::Accept(_listensock, &clientip, &clientport);
                // if(sock < 0)
                //     { continue; }
            }
        }
        ~selectServer()
        {
            if (_listensock < 0)
                close(_listensock);
            if (_fdarray)
                delete[] _fdarray;
        }

    private:
        int _port;
        int _listensock;
        int *_fdarray;
        func_t _func;
    };

}